/**
 * cart状态管理模块
 */
const cartModule = {
    namespaced:true,
    state:{
        cart:[] //购物车数组
    },
    getters:{
        /**
         * 计算处是否所有商品都选中
         * @param {*} state 
         * @returns 
         */
        allChecked(state) {
            return state.cart.every(prod => prod.checked)
        },

        /**
         * 合计金额
         * @param {*} state 
         */
        totalMoney(state) {
            return state.cart.reduce((sum,prod) => {
                if(prod.checked){
                    sum += prod.price * prod.amount
                }
                return sum
            },0) * 100
            
        },

        /**
         * 合计数量
         * @param {*} state 
         */
        totaAmount(state) {
            return state.cart.reduce((sum,prod) => {
                if(prod.checked) {
                    sum += prod.amount
                }
                return sum
            },0)
        }
    },
    mutations:{ //同步更新状态数据的mutation方法

        // 加入购物车
        addToCart(state,payload){
            //查询购物车中是否已有该商品
            const product = state.cart.find(prod => prod.id === payload.currentProduct.id)
            if(product){
                product.amount += payload.currentProduct.amount
            }else{
                state.cart.push({
                    ...payload.currentProduct,
                    checked: true
                })
            }
        },

        /**
         * 修改购物车中商品的选中状态
         */
        modifyChecked(state,payload){
            //找到购物车中的商品
            const product = state.cart.find(prod => prod.id === payload.id)
            // 修改选中状态
            product.checked = !product.checked
        },

        /**
         * 全选/取消全选
         */
        modifyAllChecked(state,payload){
            state.cart = state.cart.map(prod => {
                prod.checked = payload.allChecked
                return prod
            })
        },

        //加一
        pushOne(state,payload){
            const product = state.cart.find(prod => prod.id === payload.id )
            // console.log(product);
            product.amount += 1
            // console.log(product);
        },
        //减一
        minusOne(state,payload){
            const product = state.cart.find(prod => prod.id === payload.id )
            if(product.amount<=1){
                product.amount = 1
            }else{
                product.amount -= 1
            }
        },

        //从购物车移除商品
        removeFromCart(state,payload){
            state.cart = state.cart.filter(prod => prod.id !== payload.id)
        }

    }
}

export default cartModule